/**
 * @file ethercat_example_config.c
 * @brief 使用配置文件的EtherCAT主站接口示例
 * 
 * 该文件演示了如何使用配置文件选择EtherCAT主站类型
 */

#include "ethercat_interface.h"
#include "ethercat_config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>

/* 全局变量 */
static int running = 1;
static EtherCATInterface *ec_master = NULL;

/* 信号处理函数 */
void signal_handler(int sig) {
    running = 0;
}

/**
 * @brief 打印使用说明
 */
void print_usage(const char *program_name) {
    printf("Usage: %s [options]\n", program_name);
    printf("Options:\n");
    printf("  -t, --type <type>    指定主站类型 (igh 或 soem)\n");
    printf("  -i, --interface <if> 指定网络接口名称\n");
    printf("  -c, --config <file>  指定配置文件路径\n");
    printf("  -s, --save           保存当前设置到配置文件\n");
    printf("  -h, --help           显示此帮助信息\n");
    printf("\n如果未指定选项，将从配置文件加载设置\n");
}

/**
 * @brief 主函数
 */
int main(int argc, char *argv[]) {
    /* 默认值 */
    EtherCATMasterType master_type = DEFAULT_MASTER_TYPE;
    char ifname[256] = {0};
    const char *config_file = NULL;
    int save_config = 0;
    
    /* 解析命令行参数 */
    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-t") == 0 || strcmp(argv[i], "--type") == 0) {
            if (i + 1 < argc) {
                i++;
                if (strcmp(argv[i], "igh") == 0) {
                    master_type = MASTER_TYPE_IGH;
                } else if (strcmp(argv[i], "soem") == 0) {
                    master_type = MASTER_TYPE_SOEM;
                } else {
                    fprintf(stderr, "Unknown master type: %s\n", argv[i]);
                    print_usage(argv[0]);
                    return 1;
                }
            }
        } else if (strcmp(argv[i], "-i") == 0 || strcmp(argv[i], "--interface") == 0) {
            if (i + 1 < argc) {
                i++;
                strncpy(ifname, argv[i], sizeof(ifname) - 1);
            }
        } else if (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--config") == 0) {
            if (i + 1 < argc) {
                i++;
                config_file = argv[i];
            }
        } else if (strcmp(argv[i], "-s") == 0 || strcmp(argv[i], "--save") == 0) {
            save_config = 1;
        } else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
            print_usage(argv[0]);
            return 0;
        } else {
            fprintf(stderr, "Unknown option: %s\n", argv[i]);
            print_usage(argv[0]);
            return 1;
        }
    }
    
    /* 如果未指定主站类型，从配置文件加载 */
    if (argc == 1) {
        master_type = load_master_type_from_config(config_file);
        get_default_interface(ifname, sizeof(ifname));
    }
    
    /* 如果未指定网络接口，使用默认值 */
    if (ifname[0] == '\0') {
        get_default_interface(ifname, sizeof(ifname));
    }
    
    /* 保存配置 */
    if (save_config) {
        save_master_type_to_config(master_type, config_file);
        printf("配置已保存\n");
    }
    
    printf("使用主站类型: %s\n", master_type == MASTER_TYPE_IGH ? "IgH" : "SOEM");
    printf("使用网络接口: %s\n", ifname);
    
    /* 注册信号处理函数 */
    signal(SIGINT, signal_handler);
    
    /* 创建EtherCAT主站实例 */
    ec_master = create_ethercat_master(master_type);
    if (!ec_master) {
        fprintf(stderr, "Failed to create EtherCAT master!\n");
        return 1;
    }
    
    /* 初始化EtherCAT主站 */
    if (!ec_master->init(ifname)) {
        fprintf(stderr, "Failed to initialize EtherCAT master on %s!\n", ifname);
        destroy_ethercat_master(ec_master);
        return 1;
    }
    
    /* 配置并自动发现从站 */
    int slave_count = ec_master->config_init();
    if (slave_count <= 0) {
        fprintf(stderr, "No slaves found!\n");
        ec_master->close();
        destroy_ethercat_master(ec_master);
        return 1;
    }
    
    /* 配置过程数据映射 */
    if (!ec_master->config_map(NULL)) {
        fprintf(stderr, "Failed to configure process data mapping!\n");
        ec_master->close();
        destroy_ethercat_master(ec_master);
        return 1;
    }
    
    /* 配置分布式时钟 */
    ec_master->config_dc();
    
    /* 等待所有从站达到SAFE_OP状态 */
    printf("Waiting for all slaves to reach SAFE_OP state...\n");
    ec_master->state_check(0, EC_STATE_SAFEOP, 500000);
    
    /* 请求所有从站进入OP状态 */
    printf("Request operational state for all slaves...\n");
    ec_master->write_state(0, EC_STATE_OPERATIONAL);
    
    /* 等待所有从站达到OP状态 */
    printf("Waiting for all slaves to reach OP state...\n");
    int timeout = 500000;
    if (!ec_master->state_check(0, EC_STATE_OPERATIONAL, timeout)) {
        fprintf(stderr, "Not all slaves reached operational state!\n");
        ec_master->read_state();
        ec_master->close();
        destroy_ethercat_master(ec_master);
        return 1;
    }
    
    printf("Operational state reached for all slaves.\n");
    
    /* 循环发送/接收过程数据 */
    printf("Starting cyclic operation. Press Ctrl+C to stop.\n");
    int cycle_counter = 0;
    while (running) {
        /* 发送过程数据 */
        ec_master->send_processdata();
        
        /* 接收过程数据 */
        int wkc = ec_master->receive_processdata(1000);
        
        /* 每1000个周期打印一次信息 */
        if (cycle_counter % 1000 == 0) {
            printf("Cycle %d, WKC: %d\n", cycle_counter, wkc);
        }
        
        cycle_counter++;
        
        /* 简单延时 */
        usleep(1000);
    }
    
    printf("\nRequesting init state for all slaves...\n");
    ec_master->write_state(0, EC_STATE_INIT);
    
    /* 关闭EtherCAT主站 */
    printf("Closing EtherCAT master...\n");
    ec_master->close();
    destroy_ethercat_master(ec_master);
    
    return 0;
}